<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>新闻搜索</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 40px;
            background-color: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        /* 返回按钮样式 */
        .back-button {
            position: absolute;
            top: 20px;
            left: 20px;
            padding: 8px 12px;
            font-size: 14px;
            background-color: #6c757d;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            z-index: 10;
        }

        /* 表单容器 */
        .search-container {
            width: 100%;
            max-width: 600px;
            margin-bottom: 30px;
            text-align: center;
            position: relative; /* 用于定位返回按钮 */
        }

        .search-container label {
            font-weight: bold;
            display: block;
            margin-top: 10px;
        }

        .search-container input[type="text"],
        .search-container select {
            width: auto;
            padding: 10px;
            font-size: 16px;
            margin: 5px 0 10px 0;
            border-radius: 8px;
            border: 1px solid #ccc;
        }

        .search-container button {
            padding: 8px 16px;
            font-size: 16px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .results {
            display: flex;
            flex-direction: column;
            gap: 20px;
            width: 100%;
            max-width: 800px;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
            cursor: pointer;
            transition: transform 0.2s;
            width: 100%;
        }

        .card:hover {
            transform: scale(1.02);
        }

        .pagination {
            margin-top: 30px;
        }

        .pagination button {
            margin: 0 5px;
        }
    </style>
</head>
<body>


<div class="search-container">
    <div style="position: relative; width: 100%; text-align: center;">
        <!-- 返回按钮固定在左侧 -->
        <a href="/"
           style="position: absolute; left: 0; top: 0;
                  padding: 8px 12px;
                  font-size: 14px;
                  background-color: #6c757d;
                  color: white;
                  border: none;
                  border-radius: 4px;
                  text-decoration: none;">
            ← 返回首页
        </a>

        <!-- 标题居中 -->
        <h2 style="margin: 0; font-size: 24px;">文本搜索</h2>
    </div>

    <form id="searchForm">
        <div style="display: flex; align-items: center; gap: 10px; justify-content: center;">
            <label for="q">关键词：</label>
            <input type="text" id="q" name="q" placeholder="输入关键词..." required />

            <label for="lang">语言：</label>
            <select id="lang" name="lang">
                <option value="all">全部语言</option>
                <option value="cn">中文</option>
                <option value="en">英文</option>
            </select>

            <button type="submit">搜索</button>
        </div>
    </form>
</div>

<div id="results" class="results"></div>
<div class="pagination" id="pagination"></div>

<script>
    let currentPage = 1;
    const sizePerPage = 10;

    document.getElementById('searchForm').addEventListener('submit', function (e) {
        e.preventDefault();
        currentPage = 1;
        performSearch();
    });

    function performSearch(page = 1) {
        const formData = new FormData(document.getElementById("searchForm"));
        const params = new URLSearchParams(formData);
        params.set("page", page);

        fetch(`/api/search?${params}`)
            .then(res => res.json())
            .then(data => {
                renderResults(data.results);
                renderPagination(data.total, page, sizePerPage);
            });
    }

    function getHighlightedText(source, highlight, defaultText = "[无内容]") {
        if (highlight && highlight.length > 0) {
            return highlight[0];
        }
        return source || defaultText;
    }

    function renderResults(results) {
        const resultsDiv = document.getElementById("results");
        resultsDiv.innerHTML = "";
        if (!results.length) {
            resultsDiv.innerHTML = "<p>没有找到结果</p>";
            return;
        }

        results.forEach(item => {
            const card = document.createElement("div");
            card.className = "card";
            card.onclick = () => window.location.href = `/details?id=${item.id}`;

            card.innerHTML = `
                <h3>${item.title}</h3>
                <p>${item.content}</p>
                <small>评分: ${item.score}, ID: ${item.id}</small>
            `;

            resultsDiv.appendChild(card);
        });
    }

    function renderPagination(total, currentPage, size) {
        const totalPages = Math.ceil(total / size);
        const paginationDiv = document.getElementById("pagination");
        paginationDiv.innerHTML = "";

        const container = document.createElement("div");
        container.style.display = "flex";
        container.style.justifyContent = "center";
        container.style.alignItems = "center";
        container.style.gap = "10px";

        const prevBtn = document.createElement("button");
        prevBtn.textContent = "上一页";
        prevBtn.disabled = currentPage === 1;
        prevBtn.onclick = () => {
            if (currentPage > 1) performSearch(currentPage - 1);
        };
        container.appendChild(prevBtn);

        let start = Math.max(1, currentPage - 4);
        let end = Math.min(totalPages, start + 9);
        start = Math.max(1, end - 9);

        for (let i = start; i <= end; i++) {
            const btn = document.createElement("button");
            btn.textContent = i;
            btn.disabled = i === currentPage;
            btn.onclick = () => performSearch(i);
            container.appendChild(btn);
        }

        const nextBtn = document.createElement("button");
        nextBtn.textContent = "下一页";
        nextBtn.disabled = currentPage >= totalPages;
        nextBtn.onclick = () => {
            if (currentPage < totalPages) performSearch(currentPage + 1);
        };
        container.appendChild(nextBtn);

        const input = document.createElement("input");
        input.type = "number";
        input.placeholder = "页码";
        input.style.width = "60px";
        input.style.marginLeft = "10px";
        container.appendChild(input);

        const goBtn = document.createElement("button");
        goBtn.textContent = "跳转";
        goBtn.onclick = () => {
            const page = parseInt(input.value);
            if (page >= 1 && page <= totalPages) {
                performSearch(page);
            } else {
                alert(`请输入有效的页码（1-${totalPages}）`);
            }
        };
        container.appendChild(goBtn);

        paginationDiv.appendChild(container);
    }

    performSearch(currentPage);
</script>
</body>
</html>
